package com.wedding.study;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Json2xml33 {

    private static  int tag = 0;

    public static void main(String[] args) throws Exception {
        InputStream in = Json2xml.class.getClassLoader().getResourceAsStream("arr3.json");
        BufferedReader bf = new BufferedReader(new InputStreamReader(in));
        String str;
        StringBuffer sbf = new StringBuffer();
        while ((str = bf.readLine()) != null) {
            sbf.append(str);
        }
        bf.close();
        in.close();

        Document doc = DocumentHelper.createDocument();
        JSONArray jsonArray = JSON.parseArray(sbf.toString());
        Element root = doc.addElement("root");

        diguiarr(jsonArray, 0, root);

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter os = new XMLWriter(new FileWriter(new
                File("d:/createXml04.xml")), format);
        os.write(doc);
        // [8] 关闭资源
        os.flush();
        os.close();
    }

    // 数组中有数组,
    public static void diguiarr(JSONArray arr, int arrindex, Element parent){
        for (int i = 0; i < arr.size(); i++) {
            Object o = arr.get(i);
            if(o instanceof JSONArray){
                Element element1 = parent.addElement(i + "");
                diguiarr((JSONArray) o, i, element1);
            }else{
                Element e = parent.addElement(i + "");
                e.addText(o+"");
            }
        }
    }

}
